package com.goldplusgold.tradedelay.app.my.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.goldplusgold.imageloader.lib.GlideCircleTransform;
import com.goldplusgold.network.lib.exception.ServerException;
import com.goldplusgold.support.lib.base.fragment.BaseFragment;
import com.goldplusgold.support.lib.widget.AsyncTask;
import com.goldplusgold.tradedelay.app.R;
import com.goldplusgold.support.lib.wxapi.WechatBackMessageEvent;
import com.goldplusgold.tradedelay.app.my.networkservice.MyService;
import com.goldplusgold.tradedelay.app.my.account.UserInfo;
import com.goldplusgold.support.lib.utils.NetWorkConstant;
import com.goldplusgold.support.lib.utils.ReplaceStrByAsteriskUtil;
import com.goldplusgold.support.lib.widget.TitleView;
import com.goldplusgold.support.lib.wxapi.WeChatUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by admin on 2017/5/26.
 */

public class PersonalInfoFragment extends BaseFragment implements Handler.Callback {
    @BindView(R.id.title_view)
    TitleView titleView;
    @BindView(R.id.iv_phone)
    ImageView ivPhone;
    @BindView(R.id.iv_wechat)
    ImageView ivWechat;
    @BindView(R.id.unbind_layout)
    LinearLayout unbindLayout;
    @BindView(R.id.activity_personal_info)
    LinearLayout activityPersonalInfo;
    @BindView(R.id.id_user_name_txt)
    TextView idUserNameTxt;
    @BindView(R.id.id_iv_head_image)
    ImageView idIvHeadImage;
    @BindView(R.id.txt_nickname)
    TextView txtNickname;
    private String mHeadImage;
    private String mUserName;
    private String wechatCode;
    private String mWechatName;
    private boolean mWechatState;
    private Handler handler = new Handler(this);

    public static PersonalInfoFragment newInstance(String headImage, String userName, String wechatName, boolean wechatState) {
        Bundle args = new Bundle();
        PersonalInfoFragment fragment = new PersonalInfoFragment();
        args.putString("headImage", headImage);
        args.putString("userName", userName);
        args.putString("wechatName", wechatName);
        args.putBoolean("wechatState", wechatState);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mHeadImage = getArguments().getString("headImage");
            mUserName = getArguments().getString("userName");
            mWechatName = getArguments().getString("wechatName");
            mWechatState = getArguments().getBoolean("wechatState");
        }
        EventBus.getDefault().register(this);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_personal_info;
    }

    @Override
    protected void initView() {
        super.initView();
        titleView.getTitletextView().setVisibility(View.VISIBLE);
        titleView.getTitletextView().setText("我的信息");
        titleView.getBackView().setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(mUserName)) {
            idUserNameTxt.setText(ReplaceStrByAsteriskUtil.hideMidFourPhoneNum(mUserName));
        }
        Glide.with(getActivity()).load(mHeadImage).error(R.drawable.head_image_default).transform(new GlideCircleTransform(getActivity())).into(idIvHeadImage);
        if (mWechatState) {
            txtNickname.setVisibility(View.VISIBLE);
            txtNickname.setText(mWechatName);
        } else {
            unbindLayout.setVisibility(View.VISIBLE);
        }
    }


    @OnClick({R.id.iv_back, R.id.unbind_layout, R.id.activity_personal_info})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                getActivity().onBackPressed();
                break;
            case R.id.unbind_layout:
                WeChatUtil.getInstance().WXLogin();
                break;
            case R.id.activity_personal_info:
                break;
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        if (isAvailableActivity()) {
            int type = msg.what;
            switch (type) {

                case NetWorkConstant.NETWORK_ERROR_CODE:
                    showToastMessage(R.string.network_error, Toast.LENGTH_LONG);
                    break;
                case NetWorkConstant.NETWORK_SERVER_ERROR_CODE:
                    String errorMessage = (String) msg.obj;
                    showToastMessage(errorMessage, Toast.LENGTH_LONG);
                    break;
            }
        }
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onWechatBackEvent(WechatBackMessageEvent event) {
        wechatCode = event.getCode();
        new BindWechatAsyncTask().execute(AsyncTask.TYPE_NET);
    }


    public class BindWechatAsyncTask extends AsyncTask<Void, Void, UserInfo> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showLoadingControl();
        }

        @Override
        protected UserInfo doInBackground(Void... params) {
            try {
                UserInfo userInfo = MyService.getInstance().bindWechat(wechatCode);
                if (userInfo != null) {
                    return userInfo;
                }
            } catch (ServerException e) {

                sendNetworkErrorMessage(NetWorkConstant.NETWORK_SERVER_ERROR_CODE, e.getMessage());

            } catch (Exception e) {
                e.printStackTrace();
                sendNetworkErrorMessage(NetWorkConstant.NETWORK_ERROR_CODE, null);
            }

            return null;
        }

        @Override
        protected void onPostExecute(UserInfo userInfo) {
            super.onPostExecute(userInfo);
            dismisLoadingControl();
            if (userInfo != null) {
                txtNickname.setVisibility(View.VISIBLE);
                txtNickname.setText(userInfo.getWechatName());
                unbindLayout.setVisibility(View.GONE);
            }
        }

    }

    private void sendNetworkErrorMessage(int type, String errorMessage) {
        Message message = handler.obtainMessage();
        message.what = type;
        if (!TextUtils.isEmpty(errorMessage)) {
            message.obj = errorMessage;
        }
        handler.sendMessage(message);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
